<template>
  <div class="device-info">
    <div class="page-header">
      <h1>管廊系统设备信息</h1>
      <div class="header-actions">
        <t-button theme="primary" @click="handleAdd">
          <template #icon><t-icon name="add" /></template>
          添加设备
        </t-button>
        <t-input
          v-model="searchText"
          placeholder="搜索设备"
          style="width: 200px; margin-left: 16px"
          clearable
        >
          <template #suffix-icon>
            <t-icon name="search" @click="onSearch" />
          </template>
        </t-input>
      </div>
    </div>

    <t-tabs v-model="activeTab" :list="tabList" @change="handleTabChange" />

    <t-table
      :columns="columns"
      :data="filteredDevices"
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      bordered
      row-key="id"
    >
      <template #status="{ row }">
        <t-tag :theme="getStatusTheme(row.status)" variant="light">
          {{ row.status }}
        </t-tag>
      </template>
      <template #healthStatus="{ row }">
        <t-progress
          :percentage="row.healthStatus"
          :color="getHealthColor(row.healthStatus)"
          :label="false"
        />
        <span style="margin-left: 8px">{{ row.healthStatus }}%</span>
      </template>
      <template #op="{ row }">
        <t-space>
          <t-link theme="primary" hover="color" @click="handleEdit(row)">编辑</t-link>
          <t-link theme="primary" hover="color" @click="handleView(row)">查看详情</t-link>
          <t-link theme="danger" hover="color" @click="showDeleteConfirm(row)">删除</t-link>
        </t-space>
      </template>
    </t-table>

    <!-- 添加/编辑设备对话框 -->
    <t-dialog
      v-model:visible="modalVisible"
      :header="modalTitle"
      :confirm-loading="confirmLoading"
      @confirm="handleModalOk"
    >
      <t-form
        ref="formRef"
        :data="formState"
        :rules="rules"
        :label-width="100"
      >
        <t-form-item label="设备名称" name="name">
          <t-input v-model="formState.name" />
        </t-form-item>
        <t-form-item label="设备类型" name="type">
          <t-select v-model="formState.type">
            <t-option value="摄像头" label="摄像头" />
            <t-option value="传感器" label="传感器" />
            <t-option value="控制器" label="控制器" />
            <t-option value="网关" label="网关" />
            <t-option value="其他" label="其他" />
          </t-select>
        </t-form-item>
        <t-form-item label="所属产品" name="productId">
          <t-select v-model="formState.productId">
            <t-option v-for="product in products" :key="product.id" :value="product.id" :label="product.name" />
          </t-select>
        </t-form-item>
        <t-form-item label="安装位置" name="location">
          <t-input v-model="formState.location" />
        </t-form-item>
        <t-form-item label="安装日期" name="installDate">
          <t-date-picker v-model="formState.installDate" style="width: 100%" />
        </t-form-item>
        <t-form-item label="IP地址" name="ipAddress">
          <t-input v-model="formState.ipAddress" />
        </t-form-item>
        <t-form-item label="MAC地址" name="macAddress">
          <t-input v-model="formState.macAddress" />
        </t-form-item>
        <t-form-item label="设备状态" name="status">
          <t-select v-model="formState.status">
            <t-option value="在线" label="在线" />
            <t-option value="离线" label="离线" />
            <t-option value="故障" label="故障" />
            <t-option value="维护中" label="维护中" />
          </t-select>
        </t-form-item>
        <t-form-item label="健康状态" name="healthStatus">
          <t-slider v-model="formState.healthStatus" :marks="{ 0: '0%', 50: '50%', 100: '100%' }" />
        </t-form-item>
        <t-form-item label="备注" name="remark">
          <t-textarea v-model="formState.remark" :rows="3" />
        </t-form-item>
      </t-form>
    </t-dialog>

    <!-- 设备详情对话框 -->
    <t-dialog
      v-model:visible="detailsVisible"
      header="设备详情"
      :footer="false"
      width="800px"
    >
      <div v-if="currentDevice" class="device-details">
        <t-tabs :default-value="detailsActiveTab">
          <t-tab-panel value="basic" label="基本信息">
            <t-descriptions bordered :column="2">
              <t-descriptions-item label="设备ID" :span="1">{{ currentDevice.id }}</t-descriptions-item>
              <t-descriptions-item label="设备名称" :span="1">{{ currentDevice.name }}</t-descriptions-item>
              <t-descriptions-item label="设备类型" :span="1">{{ currentDevice.type }}</t-descriptions-item>
              <t-descriptions-item label="所属产品" :span="1">{{ getProductName(currentDevice.productId) }}</t-descriptions-item>
              <t-descriptions-item label="安装位置" :span="1">{{ currentDevice.location }}</t-descriptions-item>
              <t-descriptions-item label="安装日期" :span="1">{{ currentDevice.installDate }}</t-descriptions-item>
              <t-descriptions-item label="IP地址" :span="1">{{ currentDevice.ipAddress }}</t-descriptions-item>
              <t-descriptions-item label="MAC地址" :span="1">{{ currentDevice.macAddress }}</t-descriptions-item>
              <t-descriptions-item label="设备状态" :span="1">
                <t-tag :theme="getStatusTheme(currentDevice.status)" variant="light">
                  {{ currentDevice.status }}
                </t-tag>
              </t-descriptions-item>
              <t-descriptions-item label="健康状态" :span="1">
                <t-progress
                  :percentage="currentDevice.healthStatus"
                  :color="getHealthColor(currentDevice.healthStatus)"
                  :label="false"
                  style="width: 200px"
                />
                <span style="margin-left: 8px">{{ currentDevice.healthStatus }}%</span>
              </t-descriptions-item>
              <t-descriptions-item label="备注" :span="2">{{ currentDevice.remark || '-' }}</t-descriptions-item>
            </t-descriptions>
          </t-tab-panel>
          
          <t-tab-panel value="monitoring" label="监控数据">
            <div class="monitoring-charts">
              <div class="chart-container">
                <h3>CPU使用率</h3>
                <div class="chart-placeholder">
                  <p>此处可集成图表组件展示CPU使用率趋势</p>
                </div>
              </div>
              <div class="chart-container">
                <h3>内存使用率</h3>
                <div class="chart-placeholder">
                  <p>此处可集成图表组件展示内存使用率趋势</p>
                </div>
              </div>
              <div class="chart-container">
                <h3>网络流量</h3>
                <div class="chart-placeholder">
                  <p>此处可集成图表组件展示网络流量趋势</p>
                </div>
              </div>
            </div>
          </t-tab-panel>
          
          <t-tab-panel value="maintenance" label="维护记录">
            <t-table
              :columns="maintenanceColumns"
              :data="currentDevice.maintenanceRecords || []"
              :pagination="{ pageSize: 5 }"
              bordered
              row-key="id"
              empty="暂无维护记录"
            />
          </t-tab-panel>
        </t-tabs>
      </div>
    </t-dialog>

    <!-- 删除确认对话框 -->
    <t-dialog
      v-model:visible="deleteConfirmVisible"
      header="确认删除"
      body="确定要删除这个设备吗?"
      @confirm="confirmDelete"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import dayjs from 'dayjs';

// 产品数据
const products = ref([
  { id: '1001', name: '高清摄像机' },
  { id: '1002', name: '温湿度传感器' },
  { id: '1003', name: '气体检测仪' },
  { id: '1004', name: '智能控制器' },
]);

// 表格列定义
const columns = [
  {
    colKey: 'id',
    title: '设备ID',
    width: '80',
  },
  {
    colKey: 'name',
    title: '设备名称',
    width: '150',
  },
  {
    colKey: 'type',
    title: '设备类型',
    width: '100',
  },
  {
    colKey: 'productId',
    title: '所属产品',
    width: '150',
    cell: ({ row }) => row.productId ? getProductName(row.productId) : '-',
  },
  {
    colKey: 'location',
    title: '安装位置',
    width: '150',
  },
  {
    colKey: 'status',
    title: '设备状态',
    width: '100',
    cell: 'status',
  },
  {
    colKey: 'healthStatus',
    title: '健康状态',
    width: '150',
    cell: 'healthStatus',
  },
  {
    colKey: 'op',
    title: '操作',
    width: '180',
    cell: 'op',
  },
];

// 维护记录表格列定义
const maintenanceColumns = [
  {
    colKey: 'date',
    title: '维护日期',
    width: '150',
  },
  {
    colKey: 'type',
    title: '维护类型',
    width: '120',
  },
  {
    colKey: 'operator',
    title: '操作人员',
    width: '120',
  },
  {
    colKey: 'description',
    title: '维护内容',
  },
];

// 标签页定义
const tabList = [
  { value: 'all', label: '全部' },
  { value: 'online', label: '在线' },
  { value: 'offline', label: '离线' },
  { value: 'fault', label: '故障' },
  { value: 'maintenance', label: '维护中' },
];

// 模拟数据
const allDevices = ref([
  {
    id: 'D001',
    name: '入口摄像头',
    type: '摄像头',
    productId: '1001',
    location: '管廊入口',
    installDate: '2023-04-15',
    ipAddress: '192.168.1.101',
    macAddress: '00:1A:2B:3C:4D:5E',
    status: '在线',
    healthStatus: 95,
    remark: '监控管廊入口区域',
    maintenanceRecords: [
      {
        id: 1,
        date: '2023-08-15',
        type: '定期维护',
        operator: '张工',
        description: '清洁镜头，更新固件',
      },
      {
        id: 2,
        date: '2023-06-20',
        type: '故障修复',
        operator: '李工',
        description: '更换电源适配器',
      },
    ],
  },
  {
    id: 'D002',
    name: '温湿度传感器A',
    type: '传感器',
    productId: '1002',
    location: '管廊中段A区',
    installDate: '2023-03-10',
    ipAddress: '192.168.1.102',
    macAddress: '00:1A:2B:3C:4D:5F',
    status: '在线',
    healthStatus: 98,
    remark: '监测管廊环境温湿度',
    maintenanceRecords: [
      {
        id: 1,
        date: '2023-07-10',
        type: '定期校准',
        operator: '王工',
        description: '传感器校准，精度检测',
      },
    ],
  },
  {
    id: 'D003',
    name: '气体检测器B',
    type: '传感器',
    productId: '1003',
    location: '管廊中段B区',
    installDate: '2023-02-25',
    ipAddress: '192.168.1.103',
    macAddress: '00:1A:2B:3C:4D:60',
    status: '故障',
    healthStatus: 45,
    remark: '检测有害气体浓度',
    maintenanceRecords: [
      {
        id: 1,
        date: '2023-09-05',
        type: '故障维修',
        operator: '赵工',
        description: '更换气体传感元件',
      },
      {
        id: 2,
        date: '2023-05-15',
        type: '定期维护',
        operator: '赵工',
        description: '清洁传感器，校准参数',
      },
    ],
  },
  {
    id: 'D004',
    name: '控制器A',
    type: '控制器',
    productId: '1004',
    location: '管廊控制室',
    installDate: '2023-01-20',
    ipAddress: '192.168.1.104',
    macAddress: '00:1A:2B:3C:4D:61',
    status: '在线',
    healthStatus: 92,
    remark: '管理管廊设备控制系统',
    maintenanceRecords: [
      {
        id: 1,
        date: '2023-08-20',
        type: '系统升级',
        operator: '刘工',
        description: '升级控制系统软件',
      },
    ],
  },
  {
    id: 'D005',
    name: '网关设备',
    type: '网关',
    productId: '1004',
    location: '管廊控制室',
    installDate: '2023-01-15',
    ipAddress: '192.168.1.1',
    macAddress: '00:1A:2B:3C:4D:62',
    status: '离线',
    healthStatus: 0,
    remark: '管理管廊网络通信',
    maintenanceRecords: [
      {
        id: 1,
        date: '2023-09-10',
        type: '故障排查',
        operator: '张工',
        description: '检查网络连接问题',
      },
    ],
  },
  {
    id: 'D006',
    name: '出口摄像头',
    type: '摄像头',
    productId: '1001',
    location: '管廊出口',
    installDate: '2023-04-16',
    ipAddress: '192.168.1.105',
    macAddress: '00:1A:2B:3C:4D:63',
    status: '维护中',
    healthStatus: 60,
    remark: '监控管廊出口区域',
    maintenanceRecords: [
      {
        id: 1,
        date: '2023-09-15',
        type: '设备更新',
        operator: '李工',
        description: '更换摄像头镜头',
      },
    ],
  },
]);

const loading = ref(false);
const searchText = ref('');
const activeTab = ref('all');
const modalVisible = ref(false);
const modalTitle = ref('添加设备');
const confirmLoading = ref(false);
const formRef = ref(null);
const currentId = ref(null);
const detailsVisible = ref(false);
const currentDevice = ref(null);
const detailsActiveTab = ref('basic');
const deleteConfirmVisible = ref(false);
const deviceToDelete = ref(null);

// 表单状态
const formState = reactive({
  name: '',
  type: '摄像头',
  productId: '',
  location: '',
  installDate: null,
  ipAddress: '',
  macAddress: '',
  status: '在线',
  healthStatus: 100,
  remark: '',
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  productId: [{ required: true, message: '请选择所属产品', trigger: 'change' }],
  location: [{ required: true, message: '请输入安装位置', trigger: 'blur' }],
  installDate: [{ required: true, message: '请选择安装日期', trigger: 'change' }],
  ipAddress: [{ required: true, message: '请输入IP地址', trigger: 'blur' }],
  status: [{ required: true, message: '请选择设备状态', trigger: 'change' }],
};

// 根据标签页和搜索条件过滤设备
const filteredDevices = computed(() => {
  let result = [...allDevices.value];
  
  // 按标签页筛选
  if (activeTab.value !== 'all') {
    const statusMap = {
      online: '在线',
      offline: '离线',
      fault: '故障',
      maintenance: '维护中',
    };
    result = result.filter(device => device.status === statusMap[activeTab.value]);
  }
  
  // 按搜索文本筛选
  if (searchText.value) {
    const keyword = searchText.value.toLowerCase();
    result = result.filter(
      (device) =>
        device.name.toLowerCase().includes(keyword) ||
        device.type.toLowerCase().includes(keyword) ||
        device.location.toLowerCase().includes(keyword) ||
        device.id.toLowerCase().includes(keyword)
    );
  }
  
  return result;
});

// 获取产品名称
const getProductName = (productId) => {
  const product = products.value.find(p => p.id === productId);
  return product ? product.name : '-';
};

// 获取设备状态对应的主题色
const getStatusTheme = (status) => {
  switch (status) {
    case '在线': return 'success';
    case '离线': return 'default';
    case '故障': return 'danger';
    case '维护中': return 'warning';
    default: return 'default';
  }
};

// 获取健康状态对应的颜色
const getHealthColor = (health) => {
  if (health >= 80) return '#00a870';
  if (health >= 60) return '#ed7b2f';
  return '#e34d59';
};

// 搜索处理
const onSearch = () => {
  // 搜索逻辑已通过计算属性实现
};

// 标签页切换处理
const handleTabChange = (value) => {
  activeTab.value = value;
};

// 添加设备
const handleAdd = () => {
  resetForm();
  modalTitle.value = '添加设备';
  modalVisible.value = true;
  currentId.value = null;
};

// 编辑设备
const handleEdit = (row) => {
  modalTitle.value = '编辑设备';
  modalVisible.value = true;
  currentId.value = row.id;
  
  // 填充表单数据
  formState.name = row.name;
  formState.type = row.type;
  formState.productId = row.productId;
  formState.location = row.location;
  formState.installDate = dayjs(row.installDate).toDate();
  formState.ipAddress = row.ipAddress;
  formState.macAddress = row.macAddress;
  formState.status = row.status;
  formState.healthStatus = row.healthStatus;
  formState.remark = row.remark;
};

// 查看设备详情
const handleView = (row) => {
  currentDevice.value = { ...row };
  detailsVisible.value = true;
  detailsActiveTab.value = 'basic';
};

// 显示删除确认对话框
const showDeleteConfirm = (row) => {
  deviceToDelete.value = row;
  deleteConfirmVisible.value = true;
};

// 确认删除设备
const confirmDelete = () => {
  if (deviceToDelete.value) {
    allDevices.value = allDevices.value.filter(item => item.id !== deviceToDelete.value.id);
    MessagePlugin.success('设备已删除');
    deviceToDelete.value = null;
  }
};

// 模态框确认
const handleModalOk = () => {
  formRef.value.validate().then((result) => {
    if (result === true) {
      confirmLoading.value = true;
      
      setTimeout(() => {
        if (currentId.value) {
          // 更新设备
          const index = allDevices.value.findIndex(item => item.id === currentId.value);
          if (index !== -1) {
            allDevices.value[index] = {
              ...allDevices.value[index],
              name: formState.name,
              type: formState.type,
              productId: formState.productId,
              location: formState.location,
              installDate: dayjs(formState.installDate).format('YYYY-MM-DD'),
              ipAddress: formState.ipAddress,
              macAddress: formState.macAddress,
              status: formState.status,
              healthStatus: formState.healthStatus,
              remark: formState.remark,
            };
            MessagePlugin.success('设备已更新');
          }
        } else {
          // 添加设备
          const lastId = allDevices.value.length > 0 
            ? parseInt(allDevices.value[allDevices.value.length - 1].id.substring(1)) 
            : 0;
          const newId = `D${(lastId + 1).toString().padStart(3, '0')}`;
          
          allDevices.value.push({
            id: newId,
            name: formState.name,
            type: formState.type,
            productId: formState.productId,
            location: formState.location,
            installDate: dayjs(formState.installDate).format('YYYY-MM-DD'),
            ipAddress: formState.ipAddress,
            macAddress: formState.macAddress,
            status: formState.status,
            healthStatus: formState.healthStatus,
            remark: formState.remark,
            maintenanceRecords: [],
          });
          MessagePlugin.success('设备已添加');
        }
        
        modalVisible.value = false;
        confirmLoading.value = false;
      }, 500);
    }
  }).catch(error => {
    console.log('验证失败:', error);
  });
};

// 重置表单
const resetForm = () => {
  formState.name = '';
  formState.type = '摄像头';
  formState.productId = '';
  formState.location = '';
  formState.installDate = null;
  formState.ipAddress = '';
  formState.macAddress = '';
  formState.status = '在线';
  formState.healthStatus = 100;
  formState.remark = '';
  
  // 重置表单验证状态
  if (formRef.value) {
    formRef.value.reset();
  }
};

// 生命周期钩子
onMounted(() => {
  // 这里可以添加从API获取设备列表的逻辑
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 500);
});
</script>

<style scoped>
.device-info {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.device-details {
  margin-bottom: 20px;
}

.monitoring-charts {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-top: 16px;
}

.chart-container {
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 16px;
}

.chart-placeholder {
  height: 200px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
}
</style> 